package cn.com.zpark.jdbc.utils;

import java.sql.*;

/**
 * @PackageName: cn.com.zpark.jdbc.utils
 * @ClassName: JDBCUtils
 * @Description:JDBC工具类,注册驱动，获取连接，关闭连接
 * @author: RZS
 * @date: 2021/10/26  17:38
 */
public class JDBCUtils {
//    private static String url = "jdbc:mysql://192.168.80.142:3306/mydb2?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
//    private static String username = "root";
//    private static String password = "root";
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    // 初始化数据
    static {
        driver = "com.mysql.jdbc.Driver";
        url = "jdbc:mysql://192.168.80.142:3306/mydb2?useSSL=false&serverTimezone=UTC&characterEncoding=UTF-8";
        username = "root";
        password = "root";
    }

    /**
     * 获取连接对象
     * @return
     * @throws Exception
     */
    public static Connection getConn() throws Exception {
        // 注册驱动，获取连接，返回连接对象
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    /**
     * 关闭连接
     */
    public static void close(ResultSet res, Statement stat, Connection conn){
        if(res != null){
            try {
                res.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(stat != null){
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
